#include "assistant.h"

assistant::assistant(): proc(0){
	
	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(flushParam()));
	
}

assistant::~assistant(){

	if(proc && proc->state() == QProcess::Running){
		proc->terminate();
		proc->waitForFinished();
	}
	delete proc;

}

void assistant::showKeyword(const QString &keyWord){

	if(!startAssistant() || !keyWord.size())
		return;
	
	param.append("expandToc 2;");
	param.append("activateKeyword ");
	param.append(keyWord.toLocal8Bit() + '\0');
	timer->start(DELAY);

}

void assistant::flushParam(){

	proc->write(param);
	param.remove(0, param.size());

}

void assistant::showDocumentation(const QString &page){

	if(!startAssistant() || !page.size())
		return;
	
	param.append("expandToc 2;");
	param.append("setSource ");
	param.append("qthelp://LegoPlot/doc/" + page.toLocal8Bit() + '\0');
	timer->start(DELAY);

}

bool assistant::startAssistant(){

	if(!proc)
		proc = new QProcess();
		
	if(proc->state() != QProcess::Running){
		QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator();
		
		#if !defined(Q_OS_MAC)
			app += QLatin1String("assistant");
		#else
			app += QLatin1String("Assistant.app/Contents/MacOS/Assistant");
		#endif
		
		QStringList args;
		QString path(QCoreApplication::applicationDirPath().append("/legoplot.qhc"));
		
		args << QLatin1String("-collectionFile")
			<< QLatin1String(path.toLatin1())
			<< QLatin1String("-enableRemoteControl");
		proc->start(app, args);
		
		if(!proc->waitForStarted()){
			QMessageBox::critical(0, QObject::tr("LegoPlot"),
				QObject::tr("Nelze spustit Qt Assistant s (%1)").arg(app));
			return false;
		}
		return true;
	}
	return false;
}
